import {
    ExceptionFilter,
    Catch,
    ArgumentsHost,
    HttpException,
    HttpStatus,
} from '@nestjs/common';


@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
    catch(exception: unknown, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        const request = ctx.getRequest();

        // 1. 初始化状态码和消息
        let status = HttpStatus.INTERNAL_SERVER_ERROR;
        let message = 'Internal Server Error';
        let error: string | undefined;

        // 2. 处理 Nest 的 HttpException
        if (exception instanceof HttpException) {
            status = exception.getStatus();
            const res: any = exception.getResponse();
            // 兼容 message 是字符串或数组的情况
            if (typeof res === 'string') {
                message = res;
            } else {
                // 如果 message 是数组，取第一条
                message = Array.isArray(res.message) ? res.message[0] : res.message || message;
                error = res.error; // 例如 "Bad Request"
            }
        }
        // 3. 处理普通 Error
        else if (exception instanceof Error) {
            message = exception.message;
        }

        // 4. 防止重复发送响应头
        if (response.headersSent) {
            return; // 已发送，不再处理
        }

        // 5. 返回统一格式的 JSON 响应
        response.status(status).json({
            code: status,
            success: false,
            message: message,
            error,
            path: request.url,
            method: request.method,
            timestamp: new Date().toLocaleString(),
        })
    }
}